package fr.maistre.swarn;

import java.util.ArrayList;
import java.util.List;

public class ListRessources extends ArrayList<Ressource> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3421490744297993860L;

	@Override
	public void add(int index, Ressource element) {

	}

	@Override
	public boolean add(Ressource e) {
		int index = indexOf(e);
		if (index != -1) {
			Ressource ressource = this.get(index);
			ressource.quantity += e.quantity;
			return false;
		} else {
			return super.add(e);
		}
	}

	public boolean remove(Ressource r) {
		int index = indexOf(r);
		if (index != -1) {
			Ressource ressource = this.get(index);
			ressource.quantity -= r.quantity;
			if (ressource.quantity == 0) {
				return super.remove(r);
			}
			if (ressource.quantity < 0) {
				throw new UnsupportedOperationException(
						"ressources insufisante: " + this.toString());

			}
		} else {
			throw new UnsupportedOperationException("ressources inexistante: "
					+ this.toString());
		}
		return false;

	}

	public List<ListRessources> divide(int facteur) {
		List<ListRessources> resultsRessources = new ArrayList<ListRessources>();

		if (facteur != 0) {
			for (int j = 0; j < facteur; j++) {

				ListRessources ressources = new ListRessources();
				for (Ressource ressource : this) {
					Ressource r = new Ressource(ressource.name,
							ressource.quantity / facteur);
					ressources.add(r);
				}
				resultsRessources.add(ressources);
			}
			this.clear();
		} else {
			// TODO trhrow exeption
		}

		return resultsRessources;
	}

}
